package sparkStream

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.{SparkConf, streaming}
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

import java.util



object SparkKafka {
  def main(args: Array[String]): Unit = {
    //  1）  构建 sparkconf  本地运行，运行应用程序名称
    val conf = new SparkConf().setMaster("local[*]").setAppName("helloStream")
    // StreamingContext  需要导入依赖
    // spark streaming 可以进行流式处理，微批次处理， 间隔 2 秒
    val ssc = new StreamingContext(conf,Seconds(2))
    // spark 输出红色 info信息   --> error
    ssc.sparkContext.setLogLevel("error")
    //3）  kafka 配置  broker ，key value ，group id，消费模式
    val kfkaParams = Map[String,Object](
      "bootstrap.servers" -> "192.168.65.128:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" ->classOf[StringDeserializer],
      "group.id" -> "niit",
      "enable.auto.commit" -> (false:java.lang.Boolean)
    )
    // 4）  spark 链接kafka  订阅，topic，streamingcontext
    // topic name
    val topicName = Array("16testnew")
    val streamRdd = KafkaUtils.createDirectStream[String,String](
      ssc,
      PreferConsistent,
      Subscribe[String,String](topicName,kfkaParams)
    )

    /*//窗口函数
    val line =streamRdd.foreachRDD(
      x=>{
        if(x.isEmpty()){
          val rs1 = x.map(_.value())
        }
      }
    )*/

    // 窗口函数
    //1)拿到kafka的数据 value
    //val line=streamRdd.map(x=>fx.value()})v
    val line = streamRdd.map(_.value()) //空格,|t, 分符 是 |t
    val res = line.flatMap(_.split(" ")).map((_,1)).reduceByKeyAndWindow(
      _ + _,
      Seconds(4),
      Seconds(4)
    )


    //producer 配置项
    val property = new util.HashMap[String,Object]()
    property.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.65.128:9092")
    property.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    property.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

    //---------------producer 配置项 end-----------------
    res.foreachRDD(
      x=>{
        println("---------数据 结果--------------------")
        x.foreach(println(_))
        //构建producer发送
      }
    )


    // 返回kafka 返回的 streamRdd （一段有时间间隔的RDD）
    streamRdd.foreachRDD(
      x=>{
        if(! x.isEmpty()){  // 判断是否为空， ！ 相反
          val line = x.map(_.value())  // 匿名函数
          line.foreach(println)  // 打印
          //词频统计
          val result = line.flatMap(_.split(" ")).map((_,1)).reduceByKey(_ + _)
          result.foreach(println)

          result.foreach(
            obj =>{
              val kfkProducer = new KafkaProducer[String,String](property)
              kfkProducer.send(new ProducerRecord[String,String]("16testnew",obj.toString()))
              kfkProducer.close()

            }
          )
        }
         }
         )


    //    6）  开启ssc ，监控  kafka 数据
    ssc.start()
    ssc.awaitTermination() // 监控kafka 的数据
























  }





}
